package com.yifan.Thread;

/**
 * @Author YIFan
 * @Date 2020/6/5 23:43
 * @Version 1.0
 */
// 模拟 龟兔赛跑
public class Race  implements  Runnable{

    private static  String winner;

    public void run() {
        for (int i = 0; i <= 100; i++) {

            // 模拟 兔子睡觉
            if(Thread.currentThread().getName().equals("兔子") && i%10==0 ){
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            // 判断比赛是否结束
            boolean win = getWin(i);
            // 比赛结束了
            if(win){
                break;
            }

            System.err.println(Thread.currentThread().getName()+"--->跑 "+i+" 米");
        }
    }

    private boolean getWin(int num){
        if( winner != null){
            return  true;
        }else if(num >= 100 ) {
            // 胜利者
            winner = Thread.currentThread().getName();
            System.err.println(" winner  is   " + winner );
            return true;
        }else {
            return  false;
        }
    }

    public static void main(String[] args) {
        Race race = new Race();
        new Thread(race,"乌龟").start();
        new Thread(race,"兔子").start();
    }

}
